﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SIMS.School;
using SIMS.Global;
using SIMS.Company;
using System.Text;
using SIMS.Student;

public partial class School_CourseStudent_CreateEdit : System.Web.UI.Page
{
    protected override void Render(HtmlTextWriter writer)
    {
        foreach (GridViewRow r in gvStudent.Rows)
        {
            if (r.RowType == DataControlRowType.DataRow)
            {
                Page.ClientScript.RegisterForEventValidation
                        (r.UniqueID + "$ctl00");
                Page.ClientScript.RegisterForEventValidation
                        (r.UniqueID + "$ctl01");
            }
        }

        base.Render(writer);
    }

    protected void gvStudent_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        GridView _gridView = (GridView)sender;

        // Get the selected index and the command name
        int _selectedIndex = int.Parse(e.CommandArgument.ToString());
        string _commandName = e.CommandName;

        switch (_commandName)
        {
            case ("SingleClick"):
                //_gridView.SelectedIndex = _selectedIndex;
                //this.Message.Text += "Single clicked GridView row at index "
                //+ _selectedIndex.ToString() + "<br />";
                break;
            case ("DoubleClick"):
                //this.Message.Text += "Double clicked GridView row at index "
                //+ _selectedIndex.ToString() + "<br />";
                _gridView.SelectedIndex = _selectedIndex;
                gvStudent_SelectedIndexChanged(sender, e);
                break;
        }
    }

    protected void gvStudent_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            // Get the LinkButton control in the first cell
            //LinkButton _singleClickButton = (LinkButton)e.Row.Cells[0].Controls[0];
            // Get the javascript which is assigned to this LinkButton
            //string _jsSingle =
            //ClientScript.GetPostBackClientHyperlink(_singleClickButton, "");
            // To prevent the first click from posting back immediately
            // (therefore giving the user a chance to double click) 
            // pause the postbackfor 300 milliseconds by 
            // wrapping the postback command in a setTimeout
            //_jsSingle = _jsSingle.Insert(11, "setTimeout(\"");
            //_jsSingle += "\", 300)";
            // Add this javascript to the onclick Attribute of the row
            //e.Row.Attributes["onclick"] = _jsSingle;

            // Get the LinkButton control in the second cell
            LinkButton _doubleClickButton = (LinkButton)e.Row.Cells[1].Controls[0];
            // Get the javascript which is assigned to this LinkButton
            string _jsDouble =
            ClientScript.GetPostBackClientHyperlink(_doubleClickButton, "");
            // Add this javascript to the ondblclick Attribute of the row
            e.Row.Attributes["ondblclick"] = _jsDouble;
        }
    }


    private void ShowStudentProfile()
    {
        StudentProfile _StudentProfile = new StudentProfile();
        StudentProfileDB _StudentProfileDB = new StudentProfileDB();
        _StudentProfile = _StudentProfileDB.GetProfile(Convert.ToInt32(hidStudentProfileID.Value));
        if (_StudentProfile != null && _StudentProfile.Id > 0)
        {
            txtStudentName.Text = _StudentProfile.Profile.FirstName + " " + _StudentProfile.Profile.LastName;
        }
    }

    private void BindCourseDetail()
    {
        ddlCourseDetailList.Items.Clear();
        ddlCourseDetailList.Items.Add(new ListItem("Select", "-1"));

        CourseDetailList _courseDetailList = new CourseDetailList();
        CourseDetailDB _courseDetailDB = new CourseDetailDB();
        _courseDetailList = _courseDetailDB.GetCourseDetailList(Convert.ToInt32(hidCompanyId.Value));
        if (_courseDetailList != null && _courseDetailList.Count > 0)
        {
            foreach (CourseDetail _cd in _courseDetailList)
            {
                ddlCourseDetailList.Items.Add(new ListItem(_cd.Name, _cd.Id.ToString()));
            }
        }
    }

    private void ShowCourseDetail()
    {
        CourseDetail _courseDetail = new CourseDetail();
        CourseDetailDB _courseDetailDB = new CourseDetailDB();
        _courseDetail = _courseDetailDB.GetCourseDetail(Convert.ToInt32(ddlCourseDetailList.Text));

        if (_courseDetail != null && _courseDetail.Id > 0)
        {
            StringBuilder _strCourseDetail = new StringBuilder();
            _strCourseDetail.Append("<table cellpadding='3' cellspacing='4'>");
            _strCourseDetail.Append("<tr><td>Course:</td><td>" + _courseDetail.CourseName + "</td></tr>");
            _strCourseDetail.Append("<tr><td>Standard Level:</td><td>" + _courseDetail.StandardLevelName + "</td></tr>");
            _strCourseDetail.Append("<tr><td>Major Field:</td><td>" + _courseDetail.MajorFieldName + "</td></tr>");
            _strCourseDetail.Append("</table>");

            lblCourseDetail.Text = _strCourseDetail.ToString();
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Session[Global.CompanyId] != null)
            {
                hidCompanyId.Value = Session[Global.CompanyId].ToString();
                lblCompany.Text = Session[Global.CompanyName].ToString();

                BindCourseDetail();

                if (Request.Params["id"] != null)
                {
                    int _CourseStudentId = 0;
                    if (int.TryParse(Request.Params["id"].ToString(), out _CourseStudentId) && _CourseStudentId > 0)
                    {
                        CourseStudent _CourseStudent = new CourseStudent();
                        CourseStudentDB _CourseStudentDB = new CourseStudentDB();
                        _CourseStudent = _CourseStudentDB.GetCourseStudent(_CourseStudentId);

                        if (_CourseStudent.Id > 0)
                        {
                            if (_CourseStudent.Error.ErrorNo > 0)
                            {
                                lblMessage.Text = _CourseStudent.Error.ErrorMessage;
                            }
                            else
                            {
                                hidCourseStudentId.Value = _CourseStudentId.ToString();
                                txtRemark.Text = _CourseStudent.Remark;
                                ddlCourseDetailList.Text = _CourseStudent.CourseDetailId.ToString();
                                ddlCourseDetailList_SelectedIndexChanged(sender, e);
                                hidStudentProfileID.Value = _CourseStudent.StudentProfileId.ToString();
                                ShowStudentProfile();

                            }
                        }
                    }
                    else
                    {
                        lblMessage.Text = "Invalid parameter!";
                    }
                }
            }
            else
            {
                lblMessage.Text = "No company found!";
                btnSubmit.Enabled = false;
            }
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {
                CourseStudent CourseStudent = new CourseStudent();
                CourseStudentDB _CourseStudentDB = new CourseStudentDB();
                int _CourseStudentId = 0;

                if (int.TryParse(hidCourseStudentId.Value, out _CourseStudentId) && _CourseStudentId > 0)
                {
                    CourseStudent = _CourseStudentDB.GetCourseStudent(_CourseStudentId);
                }
                else
                {
                    CourseStudent.Id = 0;
                    CourseStudent.Error = new MyError();
                }

                if (txtRemark.Text.Trim().Length > 0)
                {
                    CourseStudent.Remark = txtRemark.Text;
                }
                else
                {
                    CourseStudent.Remark = string.Empty;
                }

                CourseStudent.CourseDetailId = Convert.ToInt32(ddlCourseDetailList.Text);
                CourseStudent.StudentProfileId = Convert.ToInt32(hidStudentProfileID.Value);
                CourseStudent.IsActive = false;

                _CourseStudentDB.Save(CourseStudent);

                if (CourseStudent.Error.ErrorNo > 0)
                {
                    if (CourseStudent.Error.ErrorNo == 1)
                    {
                        lblMessage.Text = CourseStudent.Error.ErrorMessage;
                    }
                    else
                    {
                        lblMessage.Text = "(" + CourseStudent.Error.ErrorLocation + ")";
                        lblMessage.Text += CourseStudent.Error.ErrorMessage;
                        lblMessage.Text += "<br/><br/>" + CourseStudent.Error.ErrorStack;
                    }
                }
                else if (CourseStudent.Error.ErrorNo < 0)
                {
                    lblMessage.Text = CourseStudent.Error.ErrorMessage;
                }
                else
                {
                    lblMessage.Text = "Saved successfully!";
                    Response.Redirect("default.aspx?companyid=" + hidCompanyId.Value);
                }
            }
            else
            {
                lblMessage.Text = "Invalid form.";
            }
        }
        catch (Exception Ex)
        {
            lblMessage.Text = Ex.Message;
            MyError.CreateExceptionLog(Ex, "Company_CreateEdit");
        }

    }

    protected void ddlCourseDetailList_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCourseDetailList.Items.Count > 0 && ddlCourseDetailList.SelectedIndex > 0)
        {
            ShowCourseDetail();
        }
        else
        {
            lblCourseDetail.Text = "Please select course detail.";
        }
    }


    protected void btnSearchStudentNow_Click(object sender, EventArgs e)
    {

        gvStudent.DataBind();
        mpexStudentSearch.Show();

    }

    protected void gvStudent_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtStudentName.Text = gvStudent.SelectedRow.Cells[3].Text + " " + gvStudent.SelectedRow.Cells[4].Text;
        hidStudentProfileID.Value = gvStudent.SelectedValue.ToString();
        uplMain.Update();
        mpexStudentSearch.Hide();
    }

    protected void btnSearchStudent_Click(object sender, EventArgs e)
    {
        txtStudentNameSearch.Text = txtStudentName.Text;
        gvStudent.DataBind();
        uplStudentSearch.Update();
        hidStudentProfileID.Value = "";
        txtStudentName.Text = "";
        mpexStudentSearch.Show();
    }

    protected void btnSearchStudentEnter_Click(object sender, EventArgs e)
    {
        txtStudentNameSearch.Text = txtStudentName.Text;
        gvStudent.DataBind();
        uplStudentSearch.Update();
        hidStudentProfileID.Value = "";
        txtStudentName.Text = "";
        if (gvStudent.Rows.Count == 1)
        {
            gvStudent.SelectedIndex = 0;
            gvStudent_SelectedIndexChanged(sender, e);
        }
        else
        {
            mpexStudentSearch.Show();
        }

    }

    protected void txtStudentName_TextChanged(object sender, EventArgs e)
    {
        btnSearchStudentEnter_Click(sender, e);
    }
}